#region License
// Product:
// MCM (Message-Command-Message)
// mcm-framework.net
// 
// Author:
// Pawel Idzikowski
// Cologne, Germany
// idzikowski@polenter.com
// 
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the author(s) be held liable for any damages arising from
// the use of this software.
// 
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 
//     1. The origin of this software must not be misrepresented; you must not
//       claim that you wrote the original software. If you use this software
//       in a product, an acknowledgment in the product documentation would be
//       appreciated but is not required.
// 
//     2. Altered source versions must be plainly marked as such, and must not
//       be misrepresented as being the original software.
// 
//     3. This notice may not be removed or altered from any source distribution.
// 
#endregion
using System;
using System.Threading;

namespace Polenter.Mcm
{
    /// <summary>
    /// Executes commmands in the ThreadPool. 
    /// After the work is finished invokes an event informing
    /// about the result and an eventuall eror
    /// </summary>
    public class CommandAsyncExecutor<TCommand> where TCommand : IMcmCommand
    {
        ///<summary>
        /// Start the command asynchronously. 
        /// The event ExecuteCompleted is always invoked after execution 
        /// informing about the result and an error if any.
        ///</summary>
        ///<param name="command"></param>
        public void ExecuteAsync(TCommand command)
        {
            command.ExecuteCompleted += on_command_ExecuteCompleted;
            ThreadPool.QueueUserWorkItem(executeCommand, command);
        }

        private static void executeCommand(object state)
        {
            var command = (TCommand) state;
            command.Execute();
        }

        private void on_command_ExecuteCompleted(object sender, EventArgs e)
        {
            var command = (TCommand) sender;
            command.ExecuteCompleted -= on_command_ExecuteCompleted;
            invokeExecuteCompleted(new CommandEventArgs<TCommand>(command));
        }

        ///<summary>
        /// Invoked after the command was executed. 
        /// Command itself informs about the result and an error if any.
        ///</summary>
        public event CommandEventHandler<TCommand> ExecuteCompleted;

        private void invokeExecuteCompleted(CommandEventArgs<TCommand> e)
        {
            CommandEventHandler<TCommand> handler = ExecuteCompleted;
            if (handler != null) handler(this, e);
        }
    }
}